<template>
  <div class="drawer">
    <el-drawer v-model="drawer" direction="rtl" @closed="onClosed(ruleFormRef)">
      <template #title>
        <h4>为商机【{{ businessNname }}】添加跟进</h4>
      </template>
      <template #default>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="left" label-width="auto" class="demo-ruleForm" status-icon>
          <el-form-item label="商机阶段" prop="stage_id">
            <el-select v-model="ruleForm.stage_id" placeholder="请选择客户阶段">
              <el-option v-for="item in processSelect" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进人" prop="follow_uid">
            <el-select v-model="ruleForm.follow_uid" placeholder="请选择跟进人" multiple popper-class="zw-hide_select_option" @click="openDepart" @remove-tag="changeDepart">
              <el-option v-for="item in belongUidList" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联商机" prop="business_id">
            <el-select v-model="ruleForm.business_id" placeholder="请选择关联商机">
              <el-option v-for="item in businessSelect" :key="item.business_id" :label="item.business_code" :value="item.business_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进内容" prop="content">
            <el-input v-model="ruleForm.content" rows="5" type="textarea" placeholder="请添加跟进内容" />
          </el-form-item>
          <el-form-item label="图片">
            <div class="imgs_box">
              <template v-for="(item, index) in ruleForm.images.length + 1" :key="item">
                <div v-if="index != 9" class="item">
                  <UploadImgs :url="ruleForm.images[index]" @submit="(v) => (ruleForm.images[index] = v)" @delete="ruleForm.images.splice(index, 1)" />
                  <div v-if="!ruleForm.images[index]" class="num">({{ ruleForm.images.length }}/9)</div>
                </div>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="客户打标" prop="region">
            <div>
              <el-tag v-for="tag in AllTags" :key="tag" class="mx-1" size="small" type="warning" style="margin-right: 5px" :closable="true" @close="onClose(tag)">
                {{ tag.name }}
              </el-tag>
            </div>
            <el-button @click="selecTag" size="small">选择标签</el-button>
          </el-form-item>
        </el-form>
        <div class="footer_btn">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
  <ZWDepart ref="DepartRef" @submit="getDepart" />
  <BatchLabel :titleVisible="false" ref="BatchLabelRef" @save="getTags" />
</template>

<script lang="ts" setup>
  import UploadImgs from './UploadImgs.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import BatchLabel from '@/components/BatchLabel.vue'
  import { getSetionId } from '@/utils/utils'
  import { getBusinessSelect, getProcessSelect, addFollow } from '@/api/salesleads/salesmanagement/business'
  import { reactive, ref } from 'vue'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  const drawer = ref(false)
  const emit = defineEmits(['submit'])
  const ruleFormRef = ref<FormInstance>()
  const ruleForm: any = reactive({
    business_id: '', //商机ID
    stage_id: '',
    follow_uid: [], //跟进人
    content: '', //跟进内容
    cust_tags: [], //客户标签
    images: [] //图片
  })

  const rules = reactive<FormRules>({
    stage_id: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
    follow_uid: [{ required: true, message: '请选择跟进人', trigger: 'change' }],
    content: [{ required: true, message: '请输入跟进记录', trigger: 'blur' }]
  })

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid: any, fields: any) => {
      if (valid) {
        addFollow({ ...ruleForm, follow_uid: ruleForm.follow_uid[0] }).then((res: any) => {
          ElMessage.success('添加跟进成功')
          drawer.value = false
          emit('submit')
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  const businessSelect = ref<any>([])
  const onGetSelect = () => {
    getBusinessSelect().then((res: any) => {
      console.log('下拉商机列表', res)
      businessSelect.value = res
    })
  }
  onGetSelect()
  const processSelect: any = ref([])
  const onProcess = (workflow_id: any) => {
    getProcessSelect({ workflow_id }).then((res: any) => {
      console.log('流程阶段', res)
      processSelect.value = res
    })
  }
  // 选择员工
  const belongUidList: any = ref([])
  const DepartRef = ref<any>() // 部门弹框类型
  const openDepart = () => {
    DepartRef.value.multiple = false
    DepartRef.value.selectedMember = [...belongUidList.value]
    DepartRef.value.departVisble = true
  }
  // 获取部门成员
  const getDepart = (res: any) => {
    console.log('-------获取员工--------', res)
    belongUidList.value = res
    ruleForm.follow_uid = getSetionId('id', belongUidList.value)
  }
  // 员工移除
  const changeDepart = (tag: any) => {
    console.log(tag, '------删除--------')
    belongUidList.value = belongUidList.value.filter((item: any) => item.id !== tag)
    ruleForm.follow_uid = []
    DepartRef.value.removeItem({ id: tag })
  }
  // 打开选择标签
  const BatchLabelRef: any = ref<any>() // 选择标签弹框
  const AllTags = ref<any>([])
  const selecTag = () => {
    BatchLabelRef.value.dialogData.labelChooseType = 2
    BatchLabelRef.value.chooseDataArr = [...AllTags.value]
    BatchLabelRef.value.dialogVisible = true
  }
  const getTags = (data: any) => {
    AllTags.value = data.data
    ruleForm.cust_tags = getSetionId('id', data.data)
  }
  const onClose = (tag: any) => {
    AllTags.value = AllTags.value.filter((item) => item.id != tag.id)
    ruleForm.cust_tags = getSetionId('id', AllTags.value)
  }
  const businessNname = ref()
  const handleShow = (row: any) => {
    console.log(row)
    drawer.value = true
    businessNname.value = row.name
    ruleForm.stage_id = row.stage_id
    ruleForm.business_id = +row.business_id
    getDepart([{ ...row.belong_info, check: true, type: 'user' }])
    onProcess(row.workflow_id)
  }
  const onClosed = (formEl: FormInstance | undefined) => {
    AllTags.value = []
    ruleForm.business_id = ''
    ruleForm.stage_id = ''
    ruleForm.follow_uid = []
    ruleForm.content = ''
    ruleForm.cust_tags = []
    ruleForm.images = []
    formEl?.resetFields()
  }

  defineExpose({
    handleShow
  })
</script>
<style lang="scss" scoped>
  .drawer {
    :deep(.el-overlay) {
      .el-form-item {
        .el-form-item__content {
          .el-select {
            width: 100%;
          }
          .imgs_box {
            display: grid;
            grid-template-columns: repeat(auto-fill, 110px);
            grid-gap: 10px;
            grid-auto-rows: 110px;
            .item {
              position: relative;
              .num {
                position: absolute;
                left: 45px;
                top: 65px;
                cursor: pointer;
                color: #969696;
              }
            }
          }
        }
      }
    }
  }
</style>
